import React, { useEffect, RefObject, useState } from "react";
import styles from "./index.module.scss";
import {
  Form,
  Dialog,
  Avatar,
  Toast,
  Skeleton,
  List,
  Card,
} from "antd-mobile";

// 用于微信请求
import wxfetch from "../../utils/wxfetch";
import dayjs from "dayjs";

// 路由
import { useNavigate } from "react-router-dom";

// 导入仓库
import {
  myUserToken,
  changeUser,
  myWxInfo,
  phoneOpenid,
} from "@/store/userSlice";

// 导入带有类型的属性，方法 1.
import { useAppDispatch, useAppSelector } from "../../hooks";

// 请求
import { ApiCheckLogin, ApiLogout, ApiMemberCarList, ApiMemberInfo, ApiMemberUpdate } from "@/utils/api";

// icon
import {
  UserSetOutline,
  SetOutline,
  PhonebookOutline,
} from "antd-mobile-icons";


export default () => {
  // 表单更新
  // const [form] = Form.useForm();

  // 导入仓库 2.使用属性
  const userToken = useAppSelector(myUserToken);
  const myOpenid = useAppSelector(phoneOpenid);
  // 导入仓库 2.使用方法
  const dispatch = useAppDispatch();

  // 路由跳转
  const navigate = useNavigate();
  // 初始化检验是否注册
  // const checkUserInfo = async () => {
  //   // 是否已注册
  //   const encryptedUserInfo = localStorage.getItem("encryptedUserInfo");
  //   // 是否有accessToken
  //   // const encryptedUserToken = checkUserToken();
  //   if (encryptedUserInfo) {
  //     // 有
  //     // 判断是否过期
  //     console.log("已注册过");
  //   } else {
  //     console.log("未注册过");
  //     pushRegister();
  //   }
  // };
  // 去到注册页;
  const pushRegister = () => {
    // window.location.href = "http://127.0.0.1:8080";
    navigate("/register");
  };

  // 检查并登录的member_id
  const [member_id, setMember_id] = useState(-1);

  // 骨架屏
  const [loading, setLoading] = useState(true);
  // 用户填写信息
  const [formData, setFormData] = useState({
    name: "",
    sex: 0,
    birthday: null,
    mobile: "",
    captcha: "",
    // plate_number: "",
    member_car_plate_number: "",
    // member: member,
    created_at: "",
  });

  // 请求登录状态
  const checkLogin = async () => {
    if (!myOpenid) {
      // 去到注册页
      localStorage.removeItem("encryptedUserToken");
      // localStorage.clear();
      navigate("/register");
      console.error("/register");
    }
    console.log(myOpenid, "openid");
    // console.log(formData, "formData");
    // 暂时先用手机号+
    const res = await ApiCheckLogin(myOpenid);
    if (res.code == 0) {
      //  存到仓库？
      // console.log(res.data.member_id, "member_id");
      // 当前页面使用
      setMember_id(res.data.member_id);
      // await getMemberInfo(res.data.member_id);
      return res.data.member_id;
    } else {
      await ApiLogout();
      localStorage.clear();
      navigate('/')
      console.log("未登录");
      return;
    }
  };

  // 修改user对象属性值
  const handleFieldChange = <K extends keyof RootObject>(
    fieldName: K,
    value: RootObject[K]
  ) => {
    // console.log(fieldName, value);
    setFormData((prevData) => ({
      ...prevData,
      [fieldName]: value,
    }));
  };

  //  user对象里的属性名 属性值
  const handleNameInputChange = (
    type: keyof RootObject,
    value: RootObject[keyof RootObject]
  ) => {
    // console.log("type", type);
    handleFieldChange(type, value);
  };

  // 获取会员详情信息
  const getMemberInfo = async (member_id2?: number) => {
    let my_member_id = member_id2 ? member_id2 : member_id;
    console.log(my_member_id, "my_member_id");
    if (!myOpenid) {
      console.log("需重新进入");
      return;
    }
    // console.log(my_member_id, "my_member_id");
    // 请求用户信息
    const resInfo = await ApiMemberInfo(my_member_id);
    // console.log(resInfo, "resInfo");
    if (resInfo.code != 0) {
      console.log("请求用户信息失败");
      return;
    }
    // 成功
    // 更新用户对象
    const { name, mobile, sex, birthday, member_car_plate_number, created_at } =
      resInfo.data;
    // 更新
    handleNameInputChange("name", name);
    handleNameInputChange("mobile", mobile);
    handleNameInputChange("sex", sex);
    handleNameInputChange("member_car_plate_number", member_car_plate_number);
    handleNameInputChange("created_at", created_at);
    handleNameInputChange("birthday", new Date(birthday));
    // form.setFieldsValue(formData);
    return resInfo;
  };

  // 表达提交事件
  const onFinish = (values: any) => {
    console.log("values", values);
    Dialog.alert({
      content: <pre>{JSON.stringify(values, null, 2)}</pre>,
    });
  };

  // 初始化
  const initDataFn = async () => {
    // 检测是否注册
    // await checkLogin();
    // 请求车辆列表
    try {
      await initData();
      // 请求车牌号 车辆详情
      // 二次处理
      // await mapMemberCarList();
    } finally {
      // 无论请求成功或失败，都设置 loading 为 false
      // 使用骨架屏
      setLoading(false);
    }
  };
  // 检查登录 获取member_id
  const initData = async () => {
    const my_member_id = await checkLogin();
    // console.log(userToken.access_token, userToken.openid);
    // 用于后续 获取会员详情信息
    await getMemberInfo(my_member_id);
    await getUserInfo(userToken.access_token, userToken.openid);
  };
  // 获取userInfo
  const getUserInfo = async (access_token: string, openid: string) => {
    // 校验是否有openid和session_member_id
    if (!openid) {
      console.log("没有获取openid或没有校验登录");
      // navigate("/");
      return;
    }
    console.log(access_token, openid);
    const data = await wxfetch.getUserInfoFn(access_token, openid);

    if ("openid" in data) {
      await deterName(data);
    } else {
      // 请求失败，data 是 wxErrorInfo 类型
      // 过期，清除accessToken
      if (!img) {
        // localStorage.removeItem("encryptedUserToken");
        console.error(data.errcode, data.errmsg);
        // 重新请求
        // navigate("/");
      }
    }
  };

  // 在页面加载时从localStorage获取图像数据
  const initialImg = localStorage.getItem("img") || "";
  const [img, setImg] = useState<string>(initialImg);
  // 图片上传
  const uploadImg = (e) => {
    const formdata = new FormData();
    formdata.append("headImg", e.target.files[0]);
    const file = formdata.get("headImg");

    if (file instanceof Blob) {
      const reader = new FileReader();

      reader.onload = function (event) {
        if (event.target) {
          const imageData = event.target.result;
          setImg(imageData as any);
          localStorage.setItem("img", imageData as any);
        }
      };

      reader.readAsDataURL(file);
    }
  };

  // 更新姓名性别
  const deterName = async (wxInfo: wxInfo) => {
    // console.log(wxInfo.openid, "openid");
    // 校验是否有openid和session_member_id
    if (!wxInfo.openid) {
      console.log("没有获取openid或没有校验登录");
      return;
    }
    const { headimgurl } = wxInfo;
    // 更新
    if (!img) {
      setImg(headimgurl);
      localStorage.setItem("img", headimgurl);
    }
  };
  // 挂载页面
  useEffect(() => {
    initDataFn();
  }, []);
  // 挂载页面
  // useEffect(() => {
  //   // console.log(formData, "formData");
  //   // form.setFieldsValue(formData);
  // }, [formData, form]);

  return (
    <div className={styles.form}>
      <Skeleton.Paragraph
        animated
        lineCount={10}
        style={{ display: loading ? "block" : "none" }}
      />
      <div style={{ display: !loading ? "block" : "none" }}>
        <div className="bg">
          {/* <img
            className="img"
            src="../../../public/images/bg.png"
            width={"100%"}
            alt=""
          /> */}
          <div className="blue_bg"></div>
        </div>
        <div className="home_title" style={{ marginBottom: "20px" }}>
          {/* 个人中心 */}
          <div
            className="user"
            onClick={() => {
              navigate("/Reinfo");
            }}
          >
            <Avatar
              src={img}
              style={{ "--size": "56px", "--border-radius": "50%" }}
            />
            {/* <div className="img">
              <input type="file" id="headImg" hidden onChange={uploadImg} />
              <label htmlFor="headImg">
                <div
                  className="headImg"
                  id="headImg"
                  style={{ backgroundImage: `url(${img})` }}
                ></div>
              </label>
            </div> */}
            <div className="flex-column">
              <div className="margin_bottom">{formData.name}</div>
              <div>
                {formData.mobile.replace(/(\d{3})\d+(\d{4})/, "$1****$2")}
              </div>
            </div>
          </div>
        </div>
        {/* onClick={} */}
        {/* <DemoBlock title="没有卡片标题" background="gray"> */}
        <div className="center">
          <Card className="card">
            <div className="cardInfo">
              <div
                className="car_item"
                onClick={() => {
                  navigate("/memberCar");
                }}
              >
                <span className="txt">{formData?.member_car_plate_number}</span>
                <span className="test">车牌号</span>
              </div>
              <div className="margin-right"></div>
              <div
                className="car_item"
                onClick={() => {
                  navigate("/Reinfo");
                }}
              >
                <span className="txt">
                  {dayjs(formData?.created_at)
                    .add(50, "year")
                    .format("YYYY-MM-DD")}
                </span>
                <span className="test">会员有效期</span>
              </div>
            </div>
          </Card>
        </div>
        {/* </DemoBlock> */}
        <List header="个人信息">
          <List.Item
            prefix={<UserSetOutline />}
            onClick={() => {
              navigate("/Reinfo");
            }}
          >
            会员信息
          </List.Item>
          <List.Item
            prefix={<SetOutline />}
            onClick={() => {
              navigate("/memberCar");
            }}
          >
            车牌号管理
          </List.Item>
          <List.Item
            prefix={<PhonebookOutline />}
            onClick={() => {
              navigate("/phone");
            }}
          >
            手机号修改
          </List.Item>
          <List.Item
            prefix={<PhonebookOutline />}
            onClick={() => {
              localStorage.clear();
              navigate("/");
            }}
          >
            清除登录 测试用
          </List.Item>
        </List>
      </div>
    </div>
  );
};
